package cn.hbu.zlfw.admin.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cn.hbu.zlfw.admin.entity.ScienceExpert;
import cn.hbu.zlfw.admin.service.ScienceExpertService;
import cn.hbu.zlfw.annotation.OperatorLog;
import cn.hbu.zlfw.annotation.OperatorType;
import cn.hbu.zlfw.common.util.FileHandingUtil;
import cn.hbu.zlfw.common.util.PageModel;
import cn.hbu.zlfw.common.util.DateSortUtil;
import cn.hbu.zlfw.common.util.DicSubjectUtil;
import cn.hbu.zlfw.common.util.SessionUtil;
import cn.hbu.zlfw.common.util.ShortMessageUtil;
import cn.hbu.zlfw.common.util.Utility;
import cn.hbu.zlfw.dic.entity.DicPatentState;
import cn.hbu.zlfw.dic.service.DicPatentStateService;
import cn.hbu.zlfw.dic.service.DicSchoolService;
import cn.hbu.zlfw.dic.service.DicSubjectService;
import cn.hbu.zlfw.patent.entity.Patent;
import cn.hbu.zlfw.patent.entity.PatentApply;
import cn.hbu.zlfw.patent.entity.PatentSynergy;
import cn.hbu.zlfw.patent.service.PatentApplyService;
import cn.hbu.zlfw.patent.service.PatentService;
import cn.hbu.zlfw.patent.service.PatentSynergyService;
import net.sf.json.JSONObject;

/**
 * 
 * @ClassName: ScienceExpertController
 * @Description: 科技服务人员控制层
 * @author 王鹏伟<1223443289@qq.com>
 * @date 2017年11月27日 下午9:06:23
 * @vsersion:v1.0
 */
@Controller
@RequestMapping("/scienceExpert")
public class ScienceExpertController {
	/**
	 * 日志
	 */
	public final Logger logger = LoggerFactory.getLogger(ScienceExpertController.class);
	/**
	 * 注入request response
	 */
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpServletResponse response;
	/**
	 * 注入service
	 */
	@Autowired
	private ScienceExpertService scienceExpertService;
	@Autowired
	private PatentService patentService;
	@Autowired
	private DicSubjectService dicSubjectService;
	@Autowired
	private DicPatentStateService dicPatentStateService;
	@Autowired
	private DicSchoolService dicSchoolService;
	@Autowired
	private PatentSynergyService patentSynergyService;
	@Autowired
	private PatentApplyService patentApplyService;

	/**
	 * @Title: toMain @Description: 转向后台管理界面 @return String @throws
	 */
	@OperatorLog(type = OperatorType.OTHER, description = "科技服务人员登录成功,转向后台管理界面")
	@RequestMapping("/tomain.do")
	public String toMain() {
		return "admin/main";
	}

	/**
	 * @Title: @Description: 分页查询科技服务人员已接单专利的相关信息 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "分页查询科技服务人员已接单专利的相关信息")
	@RequestMapping("/listPatentByParams.do")
	public String listPatentByParams(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		pageModel = this.patentService.listPatentByParamsToScience(pageModel, name, scienceExpert.getId());
		pageModel.setUrl("/scienceExpert/listPatentByParams.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		// 处理协助科技人员
		Map<String, String> assistNames = new HashMap<String, String>();
		for (Patent patent : patents) {
			Set<ScienceExpert> assistScienceExperts = patent.getScienceExperts();
			List<String> names = new ArrayList<String>();
			for (ScienceExpert assistScience : assistScienceExperts) {
				names.add(assistScience.getUserName());
			}
			assistNames.put(patent.getId(), Utility.getListString(names));
		}
		map.put("assistNames", assistNames);
		if (name != null && name != "")
			map.put("name", name);
		return "admin/science/recpatentlist";
	}

	/**
	 * @Title: listAssistPatentByParams @Description: 分页条件查询科技服务人员协助专利列表 @return
	 *         String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "分页条件查询科技服务人员协助专利列表")
	@RequestMapping("/listAssistPatentByParams.do")
	public String listAssistPatentByParams(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		// 协助科技服务人员专利
		pageModel = this.patentService.listAssistPatentByParamsToScience(pageModel, name, scienceExpert.getId());
		pageModel.setUrl("/scienceExpert/listAssistPatentByParams.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		map.put("dicPatentStates", dicPatentStateService.findAll());
		if (name != null && name != "")
			map.put("name", name);
		return "admin/science/assistpatentlist";
	}

	/**
	 * @Title: listAssistPatentByParams @Description:
	 *         分页条件查询科技服务人员所可以查询所有专利列表 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "分页条件查询科技服务人员所可以查询所有专利列表")
	@RequestMapping("/listAllPatentByParams.do")
	public String listAllPatentByParams(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		pageModel = patentService.listAllPatentByParamsToScience(pageModel, name, scienceExpert.getSchoolType());
		pageModel.setUrl("/scienceExpert/listAllPatentByParams.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		map.put("dicPatentStates", dicPatentStateService.findAll());
		if (name != null && name != "")
			map.put("name", name);
		return "admin/science/allpatentlist";
	}// end method

	/**
	 * 
	 * @Title: receiveApply @Description: 科技服务人员接单 @return String @throws
	 */
	@ResponseBody
	@OperatorLog(type = OperatorType.UPDATE, description = "科技服务人员接单成功")
	@RequestMapping("/receiveApply.do")
	public String receiveApply(@RequestParam(value = "patentId", required = false) String patentId) {
		if (patentId != null && patentId != "") {
			// 修改专利状态
			Patent patent = patentService.getById(patentId);
			patent.setPatentState(DicPatentState.RECEIVED);
			// 维护科技服务人员和专利之间的关系
			ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
			patent.setScienceExpert(scienceExpert);
			this.patentService.update(patent);
			String school = dicSchoolService.getSchoolByCode(scienceExpert.getSchoolType());
			ShortMessageUtil.sendReviceApplyMessage(patent.getResearcher().getPhoneNumber(), patent, scienceExpert,
					school);
			return "success";
		} else {
			return "fail";
		}
	}

	/**
	 * 
	 * @Title: finishPatentUI @Description: 转向结项页面 @return String @throws
	 */
	@OperatorLog(type = OperatorType.OTHER, description = "科技服务人员进行结项材料提交")
	@RequestMapping("/finishPatentUI.do")
	public String finishPatentUI(@RequestParam(value = "patentId", required = false) String patentId, ModelMap map) {
		map.put("patentId", patentId);
		System.out.println("-----------------------------------------------------" + patentId);
		return "admin/science/finishpatent";
	}

	/**
	 * @Title: finishPatent @Description: 专利结项 @return String @throws
	 */
	@OperatorLog(type = OperatorType.UPDATE, description = "结项成功")
	@RequestMapping("/finishPatent.do")
	public String finishPatent(@RequestParam(value = "patentId", required = false) String patentId,
			@RequestParam(value = "finishSummary", required = false) String finishSummary,
			@RequestParam(value = "sendMsg", required = false) Boolean isSendShortMsg,
			@RequestParam(value = "finishReportFile", required = false) List<MultipartFile> finishReportFile) {
		// 找到专利
		String finishNames = null;
		Patent patent = this.patentService.getById(patentId);
		System.out.println("-----------------------------------------------------" + patentId);
		patent.setFinishSummary(finishSummary);
		// 处理上传文件
		List<String> fileNames = new ArrayList<String>();
		for (int i = 1; i < finishReportFile.size(); i++) {
			String finishReportFileName = FileHandingUtil.uploadFile(finishReportFile.get(i), request);
			fileNames.add(finishReportFileName);
		}
		if (fileNames.size() > 0) {

			finishNames = Utility.getListString(fileNames);
		}
		if (null != finishNames) {
			patent.setFinishReportFileName(finishNames);
		}
		// 设置专利状态
		patent.setPatentState(DicPatentState.FINISHED);

		this.patentService.update(patent);
		String school = this.dicSchoolService.getSchoolByCode(patent.getScienceExpert().getSchoolType());
		if (isSendShortMsg)
			ShortMessageUtil.sendFinishPatentMessage(patent.getResearcher().getPhoneNumber(), patent,
					patent.getScienceExpert(), school);
		return "redirect:/scienceExpert/listPatentByParams.do";
	}
	/**
	 * @Title: finishPatent @Description: 专利结项 @return String @throws
	 */
	@OperatorLog(type = OperatorType.UPDATE, description = "结项成功")
	@RequestMapping("/finishPatentS.do")
	@ResponseBody
	public String finishPatentS(@RequestParam(value = "patentId", required = false) String patentId,
			@RequestParam(value = "finishSummary", required = false) String finishSummary,
			@RequestParam(value = "sendMsg", required = false) Boolean isSendShortMsg,
			@RequestParam(value = "finishReportFile", required = false) List<MultipartFile> finishReportFile) {
		// 找到专利
		String finishNames = null;
		Patent patent = this.patentService.getById(patentId);
		System.out.println("-----------------------------------------------------" + patentId);
		patent.setFinishSummary(finishSummary);
		// 处理上传文件
		List<String> fileNames = new ArrayList<String>();
		for (int i = 1; i < finishReportFile.size(); i++) {
			String finishReportFileName = FileHandingUtil.uploadFile(finishReportFile.get(i), request);
			fileNames.add(finishReportFileName);
		}
		if (fileNames.size() > 0) {

			finishNames = Utility.getListString(fileNames);
		}
		if (null != finishNames) {
			patent.setFinishReportFileName(finishNames);
		}
		// 设置专利状态
		patent.setPatentState(DicPatentState.FINISHED);

		this.patentService.update(patent);
		String school = this.dicSchoolService.getSchoolByCode(patent.getScienceExpert().getSchoolType());
		if (isSendShortMsg)
			ShortMessageUtil.sendFinishPatentMessage(patent.getResearcher().getPhoneNumber(), patent,
					patent.getScienceExpert(), school);
		return "redirect:/scienceExpert/listPatentByParams.do";
	}
	/**
	 * 
	 * @Title: listFinishPatentByParams @Description: 查询该科技服务人员所有结项专利 @return
	 *         String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "获取科技服务人员所有结项专利")
	@RequestMapping("/listFinishPatentByParams.do")
	public String listFinishPatentByParams(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		pageModel = patentService.listFinishPatentByParamsToScience(pageModel, name, scienceExpert.getId());
		pageModel.setUrl("/scienceExpert/listFinishPatentByParams.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		map.put("dicPatentStates", dicPatentStateService.findAll());
		if (name != null && name != "")
			map.put("name", name);
		return "admin/science/finpatentlist";
	}

	/**
	 * 
	 * @Title: listScienceExpertByParams @Description:
	 *         条件分页查询邀请列表:排除接单科技服务人员和已邀请协助人员 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "获取科技服务人员列表")
	@RequestMapping("/listInviteScienceExpertByParams.do")
	public String listInviteScienceExpertByParams(@ModelAttribute("pageModel") PageModel<ScienceExpert> pageModel,
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "patentId", required = false) String patentId, ModelMap map) {
		HttpSession session = request.getSession();
		if (patentId != null && patentId != "") {
			session.setAttribute("sessionSciencePatentId", patentId);
		}
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		List<String> scienceExpertIds = new ArrayList<String>();
		scienceExpertIds.add(scienceExpert.getId());
		Set<ScienceExpert> assistScienceExperts = this.patentService
				.getById(session.getAttribute("sessionSciencePatentId").toString()).getScienceExperts();
		if (assistScienceExperts != null && !assistScienceExperts.isEmpty()) {
			for (ScienceExpert scienceExpert2 : assistScienceExperts) {
				scienceExpertIds.add(scienceExpert2.getId());
			}
		}
		pageModel = this.scienceExpertService.listInviteScienceExpertByParams(pageModel, userName, scienceExpertIds);
		pageModel.setUrl("/scienceExpert/listInviteScienceExpertByParams.do");
		List<ScienceExpert> scienceExperts = pageModel.getList();
		if (scienceExperts != null && !scienceExperts.isEmpty()) {
			// 解析学科信息
			map.put("scienceExpertsChars",
					DicSubjectUtil.parseSubjectByScienceExperts(scienceExperts, dicSubjectService));
		}
		map.put("dicSchools", this.dicSchoolService.findAll());
		map.put("patentId", session.getAttribute("sessionSciencePatentId").toString());
		return "admin/science/invitescience";
	}

	/**
	 * 
	 * @Title: confirmInviteScience @Description: 确定协助关系 @return String @throws
	 */
	@ResponseBody
	@OperatorLog(type = OperatorType.UPDATE, description = "完成邀请协助科技服务人员")
	@RequestMapping("/confirmInviteScience.do")
	public String confirmInviteScience(@RequestParam(value = "patentId", required = false) String patentId,
			@RequestParam(value = "scienceId", required = false) String scienceId) {
		Patent patent = this.patentService.getById(patentId);
		ScienceExpert scienceExpert = this.scienceExpertService.getById(scienceId);
		scienceExpert.getAssistPatents().add(patent);
		this.scienceExpertService.update(scienceExpert);
		return "success";
	}

	/**
	 * 
	 * @Title: listPatentOfSubjectRelated @Description:
	 *         分页查询和科技服务人员学科相关的未接单专利 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "分页查询与科技服务人员学科相关的未接单专利")
	@RequestMapping("/listPatentOfSubjectRelated.do")
	public String listPatentOfSubjectRelated(@ModelAttribute("pageModel") PageModel<Patent> pageModel,
			@RequestParam(value = "name", required = false) String name, ModelMap map) {
		int currentPage = pageModel.getCurrentPage();
		if (currentPage == 0) {
			pageModel.setCurrentPage(1);
		}
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		pageModel = patentService.listPatentOfSubjectRelatedToScience(pageModel, name, scienceExpert);
		pageModel.setUrl("/scienceExpert/listPatentOfSubjectRelated.do");
		List<Patent> patents = pageModel.getList();
		if (patents != null && !patents.isEmpty()) {
			// 解析学科信息
			map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		}
		map.put("dicPatentStates", dicPatentStateService.findAll());
		if (name != null && name != "")
			map.put("name", name);
		return "admin/science/subjectpatentlist";
	}

	/**
	 * @Title: cancelFinishPatent @Description: 科技服务人员取消结项:设置专利状态， @return
	 *         String @throws
	 */
	@OperatorLog(type = OperatorType.UPDATE, description = "科技服务人员取消结项")
	@RequestMapping("/cancelFinishPatent.do")
	public String cancelFinishPatent(@RequestParam(value = "patentId", required = false) String patentId) {
		Patent patent = this.patentService.getById(patentId);
		patent.setPatentState(DicPatentState.RECEIVED);
		this.patentService.update(patent);
		return "redirect:/scienceExpert/listFinishPatentByParams.do";
	}

	/**
	 * 
	 * @Title: listPatentSynergyByPatent @Description: 查询某个专利专利协同申请书的所有版本 @return
	 *         String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "查询某个专利专利协同申请书的所有版本")
	@RequestMapping("/listPatentSynergyByPatent.do")
	public String listPatentSynergyByPatent(@RequestParam(value = "patentId", required = false) String patentId,
			@RequestParam(value = "location", required = false) String location, ModelMap map) {
		Patent patent = this.patentService.getById(patentId);
		List<Patent> patents = new ArrayList<Patent>();
		patents.add(patent);
		Set<PatentSynergy> tempPatentSynergies = patent.getPatentSynergies();
		List<PatentSynergy> patentSynergies = DateSortUtil.sortSynergyByCTimeDEC(tempPatentSynergies);
//		try {
//			map.put("location", new String(location.getBytes("ISO-8859-1"), "UTF-8"));
//		} catch (UnsupportedEncodingException e) {
//			map.put("location", location);
//		}

		map.put("location", location);
		map.put("patentSynergies", patentSynergies);
		map.put("patent", patent);
		map.put("patentSubjectsChars", DicSubjectUtil.parseSubjectByPatents(patents, dicSubjectService));
		return "admin/science/patentSynergy";
	}

	/**
	 * 
	 * 
	 * 
	 * @Title: getPatentSynergyById @Description: 通过id查询专利协作申请书 @return
	 *         String @throws
	 */
	@ResponseBody
	@OperatorLog(type = OperatorType.SELECT, description = "通过ID查询专利协作申请书")
	@RequestMapping(value = "/getPatentSynergyById.do", produces = { "text/html;charset=UTF-8;" })
	public String getPatentSynergyById(@RequestParam(value = "synergyId", required = false) String synergyId) {
		PatentSynergy patentSynergy = this.patentSynergyService.getById(synergyId);
		return patentSynergy.getAbstractInfo();
	}

	/**
	 * 
	 * @Title: listPatentApplyByPatent @Description: 查询某个专利专利交底书的所有版本 @return
	 *         String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "查询某个专利专利交底书的所有版本")
	@RequestMapping("/listPatentApplyByPatent.do")
	public String listPatentApplyByPatent(@RequestParam(value = "patentId", required = false) String patentId,
			@RequestParam(value = "location", required = false) String location, ModelMap map) {
		Patent patent = this.patentService.getById(patentId);
		Set<PatentApply> tempPatentApplies = patent.getPatentApplies();
		List<PatentApply> patentApplies = DateSortUtil.sortApplyByCTimeDEC(tempPatentApplies);
		map.put("patentApplies", patentApplies);
		map.put("patent", patent);
		map.put("location", location);
//		try {
//			map.put("location", new String(location.getBytes("ISO-8859-1"), "UTF-8"));
//		} catch (UnsupportedEncodingException e) {
//			map.put("location", location);
//		}
		return "admin/science/patentApply";
	}

	/**
	 * 
	 * @Title: downloadFile @Description: 下载附件 @return String @throws
	 */
	@ResponseBody
	@OperatorLog(type = OperatorType.OTHER, description = "下载附件")
	@RequestMapping("/downloadFile.do")
	public String downloadFile(@RequestParam(value = "filename", required = false) String filename) {
		FileHandingUtil.downloadFile(filename, response, request);
		return null;
	}

	/**
	 * 
	 * @Title: getPatentApplyById @Description: 通过id查询专利交底书 @return String @throws
	 */
	@ResponseBody
	@OperatorLog(type = OperatorType.SELECT, description = "通过ID查询专利交底书")
	@RequestMapping(value = "/getPatentApplyById.do", produces = { "text/html;charset=UTF-8;" })
	public String getPatentApplyById(@RequestParam(value = "applyId", required = false) String applyId) {
		PatentApply patentApply = this.patentApplyService.getById(applyId);
		patentApply.setPatent(null);
		JSONObject jobj = JSONObject.fromObject(patentApply);
		return jobj.toString();
	}

	/**
	 * 
	 * @Title: finishReport @Description: 查询结项报告 @return String @throws
	 */
	@OperatorLog(type = OperatorType.SELECT, description = "查看结项报告")
	@RequestMapping("/finishReport.do")
	public String finishReport(@RequestParam(value = "patentId", required = false) String patentId, ModelMap map) {
		Patent patent = this.patentService.getById(patentId);
		map.put("finishSummary", patent.getFinishSummary());
		map.put("uploadFileNames", patent.getFinishReportFileName());
		return "admin/science/finishReport";
	}

	/**
	 * 
	 * @Title: updateScinece @Description: TODO 转向修改个人信息界面 @param: @param
	 *         patentId @param: @param map @param: @return @return: String @throws
	 */
	@RequestMapping("/toupdateScinece.do")
	public String toupdateScinece(ModelMap map) {
		ScienceExpert scienceExpert = (ScienceExpert) SessionUtil.getLoginUser(request);
		map.put("scienceExpert", scienceExpert);
		map.put("dicSchools", this.dicSchoolService.findAll());
		map.put("subjects", dicSubjectService.findAll());
		System.out.println(1234546);
		return "admin/science/updateScience";
	}

	/**
	 * 
	 * @Title: updateScinece @Description: TODO 修改科技服务人员 @param: @param
	 *         map @param: @return @return: String @throws
	 */
	@RequestMapping("/updateScinece.do")
	public String updateScinece(ModelMap map, @ModelAttribute ScienceExpert scienceExpert) {
		ScienceExpert scienceExpert1 = (ScienceExpert) SessionUtil.getLoginUser(request);
		scienceExpert1.setPassword(scienceExpert.getPassword());
		scienceExpert1.setQQ(scienceExpert.getQQ());
		scienceExpert1.setWeChat(scienceExpert.getWeChat());
		scienceExpertService.update(scienceExpert1);
		return "forward:/scienceExpert/toupdateScinece.do";
	}
}
